import requests
from config import settings

BAIDU_OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": settings.BAIDU_OCR_API_KEY,
        "client_secret": settings.BAIDU_OCR_SECRET_KEY
    }
    return requests.get(url, params=params).json().get("access_token")

def recognize_invoice(image_url):
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = {
        "access_token": get_access_token(),
        "url": image_url
    }
    response = requests.post(BAIDU_OCR_URL, headers=headers, data=data)
    #return response.json()
    ocr_data = response.json()
    print("OCR 返回的完整数据:", ocr_data)  # 打印 OCR 返回的完整数据
    return ocr_data